package org.aseclipse.core.runtime.app
{
    import mx.core.IContainer;
    
    /*******
    * The application manager
    * 1) hold all application definition
    * 2) start application 
    */ 
    public class AppManager
    {
        private var apps:Array = new Array();
        private var map:Object = new Object();
        
        public function AppManager()
        {
        }
        
        public function hasApp(id:String):Boolean {
            return map[id] != null;
        }
        
        public function getApps():Array {
            return apps;
        }
        
        public function getApp(id:String):AppDescriptor {
            return map[id] as AppDescriptor;
        }
        
        public function addApp(id:String, app:AppDescriptor):void {
            if(hasApp(id)) return;
            apps.push(app);
            map[id] = app;
        }
        
        // start specified application
        public function startApp(id:String, parent:IContainer):void {
            var context:ApplicationContext = new ApplicationContext();
            context.setParent(parent);
            (map[id] as AppDescriptor).startOn(context);
        }
        
        // check which application is suitable to start
        public function autoStart(parent:IContainer):void {
            for each(var app:AppDescriptor in apps) {
                if(app.match()) {
                    var context:ApplicationContext = new ApplicationContext();
                    context.setParent(parent);
                    context.setBrandingName(app.getLabel());
                    app.startOn(context);
                    break;
                }
            }
        }
        
    }
}